package com.rq.download_okhttp;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Parcelable;

/**
 * 记录下载位置的sp工具类
 */
class SPDownloadUtil {

    private static SharedPreferences mSharedPreferences;
    private static SPDownloadUtil instance;

    private SPDownloadUtil() {
    }

    public static SPDownloadUtil getInstance() {
        if (mSharedPreferences == null || instance == null) {
            synchronized (SPDownloadUtil.class) {
                if (mSharedPreferences == null || instance == null) {
                    instance = new SPDownloadUtil();
                    mSharedPreferences = DownloadUtil.getCtx().getSharedPreferences(DownloadUtil.getCtx().getPackageName() + ".downloadSp", Context.MODE_PRIVATE);
                }
            }
        }
        return instance;
    }

    /**
     * 清空数据
     *
     * @return true 成功
     */
    public boolean clear() {
        return mSharedPreferences.edit().clear().commit();
    }

    /**
     * 保存数据
     *
     * @param key    键
     * @param object 保存的value
     */
    public boolean save(String key, Object object) {
        if (object instanceof String) {
            return mSharedPreferences.edit().putString(key, (String) object).commit();
        } else if (object instanceof Integer) {
            return mSharedPreferences.edit().putInt(key, (int) object).commit();
        } else if (object instanceof Boolean) {
            return mSharedPreferences.edit().putBoolean(key, (Boolean) object).commit();
        } else if (object instanceof Float) {
            return mSharedPreferences.edit().putFloat(key, (Float) object).commit();
        } else if (object instanceof Long) {
            return mSharedPreferences.edit().putLong(key, (Long) object).commit();
        }
        return false;
    }

    public boolean remove(String key) {
        return mSharedPreferences.edit().remove(key).commit();
    }


    /**
     * 获取保存的数据
     *
     * @param key      键
     * @param defValue 默认返回的value
     * @return value
     */
    public long get(String key, long defValue) {
        return mSharedPreferences.getLong(key, defValue);
    }

    public <T> T get(String key, T object) {
        if (object instanceof String) {
            return (T) mSharedPreferences.getString(key, (String) object);
        } else if (object instanceof Integer) {
            return (T) Integer.valueOf(mSharedPreferences.getInt(key, (Integer) object));
        } else if (object instanceof Boolean) {
            return (T) Boolean.valueOf(mSharedPreferences.getBoolean(key, (Boolean) object));
        } else if (object instanceof Float) {
            return (T) Float.valueOf(mSharedPreferences.getFloat(key, (Float) object));
        } else if (object instanceof Long) {
            return (T) Long.valueOf(mSharedPreferences.getLong(key, (Long) object));
        }
        return null;
    }

}
